package cn.lovecyy.mockjson.core.funcs;

import cn.lovecyy.mockjson.core.domain.TypeConfig;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * DateFormatFunc
 *
 * @author Yakir
 */
public class DateFormatFunc implements FuncMock {

	@Override
	public String getFuncName() {
		return "fmtDate";
	}

	@Override
	public Object apply(TypeConfig config, String... args) {
		if (args == null || args.length < 2)
			return args != null && args.length > 0 ? args[0] : null;
		String value = args[0];
		String srcPattern = args[1];
		String dscPattern = args[2];
		String type = config.getType();
		try {

			// 尝试解析为LocalDateTime
			if ("date".equals(type)) {
				LocalDate date = LocalDate.parse(value, DateTimeFormatter.ofPattern(srcPattern));
				return date.format(DateTimeFormatter.ofPattern(dscPattern));
			}
			else if ("datetime".equals(type)) {
				LocalDateTime dateTime = LocalDateTime.parse(value, DateTimeFormatter.ofPattern(srcPattern));
				return dateTime.format(DateTimeFormatter.ofPattern(dscPattern));
			}
			else {
				// 默认直接返回原值
				return value;
			}
		}
		catch (Exception e) {
			return value;
		}
	}

}
